//
//  KYVScrollToolBarView.m
//  BeanVideo
//
//  Created by zhangliang on 2017/4/24.
//  Copyright © 2017年 zhangliang. All rights reserved.
//

#import "KYVScrollToolBarView.h"

@implementation KYVScrolLToolBarAppearance

- (instancetype)init {
    self = [super init];
    if (self) {
        self.titleFont = [UIFont systemFontOfSize:14];
        self.titleViewHeight = 44;
        self.titleOffset = 8;
        self.titleMargin = 20;
        self.bottomLineHeight = 2;
        self.maxScaleRatio = 1.2;
        self.colorNormal = __ColorHex(0xb3b3b3);
        self.colorSelected = __ColorHex(0xffb10b);
        self.isScrollEnable = YES;
        self.isShowBottomLine = YES;
        self.isBottomLineAnimation = NO;
        self.isNeedScale = YES;
        self.bottomLineColor = self.colorNormal;
    }
    return self;
}

@end


@interface KYVScrollToolBarView ()
{
    NSMutableArray<UILabel *> *_itemContainer;
    CGRect _selfFrame;
}

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIView *bottomLine;

@end

static long tagBase = 300;

@implementation KYVScrollToolBarView

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.scrollsToTop = NO;
    }
    return _scrollView;
}

- (UIView *)bottomLine {
    if (!_bottomLine) {
        _bottomLine = [UIView new];
        _bottomLine.backgroundColor = _appearance.colorSelected;
    }
    return _bottomLine;
}

- (void)setAppearance:(KYVScrolLToolBarAppearance *)appearance {
    _appearance = appearance;
}

- (KYVScrollToolBarView *)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _selfFrame = frame;
        self.selectIndex = 0;
        _itemContainer = [NSMutableArray array];
        self.appearance = [[KYVScrolLToolBarAppearance alloc] init];
        //[self setupSubViews];
    }
    return self;
}
- (KYVScrollToolBarView *)initWithFrame:(CGRect)frame items:(NSArray *)items {
    if (self = [super initWithFrame:frame]) {
        _selfFrame = frame;
        self.selectIndex = 0;
        self.items = items;
        _itemContainer = [NSMutableArray array];
        self.appearance = [[KYVScrolLToolBarAppearance alloc] init];
        [self setupSubViews];
    }
    return self;
}

- (void)setItems:(NSArray<KYVBangItem *> *)items {
    _items = items;
    if (self.subviews.count) {
        [self removeAllSubviews];
        self.selectIndex = 0;
        
    }
    [self setupSubViews];
}

- (void)setupSubViews {
    [self addSubview:self.scrollView];
    [self setupItems];
    !_appearance.isNeedScale ? : [self setupItemScale];
    !_appearance.isShowBottomLine ? : [self setupBottomLine];
    
}

- (void)setupItems {
    for (NSUInteger i = 0; i < self.items.count; i++) {
        KYVBangItem *item = self.items[i];
        UILabel *titleLabel = [UILabel new];
        [_itemContainer addObject:titleLabel];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = _appearance.titleFont;
        titleLabel.textColor = _appearance.colorNormal;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.userInteractionEnabled = YES;
        titleLabel.text = item.name;
        titleLabel.tag = i + tagBase;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapItem:)];
        [titleLabel addGestureRecognizer:tap];
        [self.scrollView addSubview:titleLabel];
    }
    CGFloat X = 0;
    CGFloat Y = 0;
    CGFloat W = _selfFrame.size.width / (CGFloat)_items.count;
    CGFloat H = _appearance.titleViewHeight;
    for (NSUInteger i = 0; i < _itemContainer.count; i++) {
        if (_appearance.isScrollEnable) {
            W = [_itemContainer[i].text sizeWithFont:_appearance.titleFont maxWidth:MAXFLOAT].width;
            X = _itemContainer[i].tag == (tagBase + 0) ? _appearance.titleOffset : (CGRectGetMaxX(_itemContainer[i - 1].frame) + _appearance.titleMargin);
        } else {
            X = W * i;
        }
        _itemContainer[i].frame = CGRectMake(X, Y, W, H);
    }
    if (_appearance.isScrollEnable) {
        CGSize size = CGSizeMake(CGRectGetMaxX(_itemContainer.lastObject.frame)+_appearance.titleOffset, _appearance.titleViewHeight);
        [self.scrollView setContentSize:size];
    }
    if (self.scrollView.contentSize.width < __widthScreen) {
        _appearance.isScrollEnable = NO;
    }
}

- (void)setupBottomLine {
    [self.scrollView addSubview:self.bottomLine];
    CGFloat x = _itemContainer.firstObject.frame.origin.x;
    CGFloat h = _appearance.bottomLineHeight;
    CGFloat y = _selfFrame.size.height - h;
    CGFloat w = _itemContainer.firstObject.frame.size.width;
    self.bottomLine.frame = CGRectMake(x, y, w, h);
}

- (void)setupItemScale {
    _itemContainer.firstObject.transform = CGAffineTransformMakeScale(_appearance.maxScaleRatio, _appearance.maxScaleRatio);
    _itemContainer.firstObject.textColor = _appearance.colorSelected;
}

- (void)tapItem:(UITapGestureRecognizer *)tap {
    // 手动选中的Item
    UILabel *selectItem = (UILabel *)tap.view;
    if (![selectItem isKindOfClass:[UILabel class]]) {
        return;
    }
    if ((selectItem.tag - tagBase) == _selectIndex) {
        return;
    }
    // 前一个Item
    UILabel *sourceItem = _itemContainer[_selectIndex];
    selectItem.textColor = _appearance.colorSelected;
    sourceItem.textColor = _appearance.colorNormal;
    NSUInteger _lastIndex = _selectIndex;
    NSUInteger _newSelectIndex = (selectItem.tag - tagBase);
    if (self.delegate && [self.delegate respondsToSelector:@selector(scrollToolBarView:lastIndex:selectIndex:)]) {
        [self.delegate scrollToolBarView:self lastIndex:_lastIndex selectIndex:_newSelectIndex];
        self.selectIndex = _newSelectIndex;
    } else {
        !_ClickedScrollBarItem ? : _ClickedScrollBarItem(_lastIndex, _newSelectIndex);
        self.selectIndex = _newSelectIndex;
    }
    [self updateSelectItemPosition];
    
    if (_appearance.isNeedScale) {
        [UIView animateWithDuration:0.25 animations:^{
            sourceItem.transform = CGAffineTransformIdentity;
            selectItem.transform = CGAffineTransformMakeScale(_appearance.maxScaleRatio, _appearance.maxScaleRatio);
        }];
    }
    if (_appearance.isShowBottomLine) {
        CGRect frame = CGRectMake(selectItem.frame.origin.x, _bottomLine.frame.origin.y, selectItem.frame.size.width, _bottomLine.frame.size.height);
        [UIView animateWithDuration:0.25 animations:^{
            self.bottomLine.frame = frame;
        }];
    }
    
}

// 这个是要根据需要，如果item所在位置即将
- (void)updateSelectItemPosition {
    if (!_appearance.isScrollEnable) {
        return;
    }
    UILabel *_selectedItem = _itemContainer[_selectIndex];
    CGFloat offsetX = _selectedItem.center.x - _scrollView.frame.size.width*0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = _scrollView.contentSize.width - _scrollView.frame.size.width;
    if (maxOffsetX > 0) {
        if (offsetX > maxOffsetX) {
            offsetX = maxOffsetX;
        }
    }
    
    [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
}

- (void)setSelectIndex:(NSUInteger)selectIndex {
    _selectIndex = selectIndex;
    if (!_appearance.isScrollEnable) {
        return;
    }
    UILabel *_selectedItem = _itemContainer[_selectIndex];
    CGFloat offsetX = _selectedItem.center.x - _scrollView.frame.size.width*0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = _scrollView.contentSize.width - _scrollView.frame.size.width;
    if (maxOffsetX > 0) {
        if (offsetX > maxOffsetX) {
            offsetX = maxOffsetX;
        }
    }
    
    [_scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

// 这个用于控制器在横向滑动的时候 方式1
- (void)scrollSuperTarget:(UIView *)contentView
            currentOffset:(CGFloat)currentOffsetX {
    CGFloat collectionWidth = contentView.width;
    NSInteger indexFrom = self.selectIndex;
    BOOL _isBack = NO;
    float progress = 0;
    
    if (indexFrom * collectionWidth > currentOffsetX) {
        progress = (indexFrom*collectionWidth - currentOffsetX)/collectionWidth;
        _isBack = YES;
    }else {
        progress = (currentOffsetX - indexFrom * collectionWidth)/collectionWidth;
    }
    [self scrollSuperTarget:contentView didScrollProgress:progress back:_isBack];
}

// 这个用于控制器在横向滑动的时候
- (void)scrollSuperTarget:(UIView *)contentView
        didScrollProgress:(CGFloat)progress
                     back:(BOOL)isBack {
    if (isBack) {
        if (self.selectIndex == 0) {
            return;
        }
    }else {
        if (self.selectIndex == self.items.count-1) {
            return;
        }
    }
    
    if (progress >= 0.99) {
        self.selectIndex = isBack?(_selectIndex-1):(_selectIndex+1);
        return;
    }
    if (progress <= 0.01) {
        return;
    }
    
    UILabel *sourceItem = _itemContainer[_selectIndex];
    UILabel *targetItem = _itemContainer[isBack?(_selectIndex-1):(_selectIndex+1)];
    
    [self colorGradientProgress:progress SorceItem:sourceItem targetItem:targetItem];
}

/**
 * 这是在外部滑动scrollView子类的时候调用
 * 此方法存在bug 滑动过快的时候会出现字体颜色乱变，指示线乱跳
 */
- (void)scrollSuperTarget:(id)target startOffset:(CGFloat)startOffset currentOffset:(CGFloat)currentOffset contentWidth:(CGFloat)contentWidth {
    CGFloat _startOffsetX = startOffset;
    CGFloat contentOffsetX = currentOffset;
    if (contentOffsetX != _startOffsetX) {} else {
        return;
    }
    NSUInteger sourceIndex = 0;
    NSUInteger targetIndex = 0;
    CGFloat progress = 0;
    BOOL isBack = NO;
    
    CGFloat collectionWidth = contentWidth;
    if (contentOffsetX > _startOffsetX) { // 左滑
        sourceIndex = (NSUInteger)contentOffsetX/collectionWidth;
        targetIndex = sourceIndex + 1;
        if (targetIndex >= self.items.count || self.selectIndex > self.items.count -1) {
            return;
        }
        progress = (contentOffsetX - _startOffsetX) / collectionWidth;
        
        if ((contentOffsetX - _startOffsetX) == collectionWidth) {
            targetIndex = sourceIndex;
        }
        
    } else { // 右滑
        if (self.selectIndex == 0) {
            return;
        }
        isBack = YES;
        targetIndex = (NSUInteger)contentOffsetX / collectionWidth;
        sourceIndex = targetIndex + 1;
        progress = (_startOffsetX - contentOffsetX) / collectionWidth;
        
    }
    if (progress > 0.99) {
        self.selectIndex = targetIndex;
        return;
    }
    if (progress <= 0.01 ) {
        return;
    }
    UILabel *sourceItem = _itemContainer[sourceIndex];
    UILabel *targetItem = _itemContainer[targetIndex];
    [self colorGradientProgress:progress SorceItem:sourceItem targetItem:targetItem];
}

/**
 * 私有方法用于颜色渐变
 */
- (void)colorGradientProgress:(CGFloat)progress SorceItem:(UILabel *)sourceItem targetItem:(UILabel *)targetItem {
    //颜色渐变
    ColorRGB rgbNormal = self.appearance.colorNormal.rgb;
    ColorRGB rgbSelect = self.appearance.colorSelected.rgb;
    sourceItem.textColor = [UIColor colorWithRed:(rgbSelect.red - (rgbSelect.red-rgbNormal.red)*progress)/255.0
                                           green:(rgbSelect.green - (rgbSelect.green-rgbNormal.green)*progress)/255.0
                                            blue:(rgbSelect.blue - (rgbSelect.blue-rgbNormal.blue)*progress)/255.0
                                           alpha:1];
    targetItem.textColor = [UIColor colorWithRed:(rgbNormal.red + (rgbSelect.red-rgbNormal.red)*progress)/255.0
                                           green:(rgbNormal.green + (rgbSelect.green-rgbNormal.green)*progress)/255.0
                                            blue:(rgbNormal.blue + (rgbSelect.blue-rgbNormal.blue)*progress)/255.0
                                           alpha:1];
    if (_appearance.isNeedScale) {
        //大小渐变 效果显示为字号渐变
        CGFloat deltaScale = _appearance.maxScaleRatio - 1.0;
        sourceItem.transform = CGAffineTransformMakeScale(_appearance.maxScaleRatio - deltaScale*progress, _appearance.maxScaleRatio - deltaScale*progress);
        targetItem.transform = CGAffineTransformMakeScale(1.0+deltaScale*progress, 1.0+deltaScale*progress);
    }
    if (_appearance.isBottomLineAnimation) {
        // 在考虑如何实现
    } else {
        // bottomLine 的变化
        CGFloat deltaWidth = targetItem.frame.size.width - sourceItem.frame.size.width;
        CGFloat deltaX = targetItem.frame.origin.x - sourceItem.frame.origin.x;
        if (_appearance.isShowBottomLine) {
            _bottomLine.width = deltaWidth * progress + sourceItem.frame.size.width;
            _bottomLine.left = deltaX * progress + sourceItem.frame.origin.x;
        }
    }
}

@end
